package rssgate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rssgate.dao.PMF;
import rssgate.dao.entity.Feed;
import rssgate.dao.entity.RSSItem;
import rssgate.util.LogUtils;

import com.google.appengine.api.datastore.Text;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

@SuppressWarnings("serial")
public class RssgateServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(RssgateServlet.class
			.getName());	
	private PrintWriter writer;
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setCharacterEncoding("UTF-8");
		writer = resp.getWriter();
		resp.setContentType("text/xml");
		String attribute = req.getPathInfo();
		if(attribute!=null)
		{
			attribute=attribute.replaceFirst("/", "");
		}
		//resp.getWriter().println("Hello, world");
		
		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("rss_2.0");
		
		final List<SyndEntry> feedEntries = new ArrayList<SyndEntry>();
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		
		String query=null;
		if(attribute==null || attribute.length()==0)
		{
			query = "select from " + Feed.class.getName();
		}
		else
		{
			query = "select from " + Feed.class.getName() + " where id=="+attribute;
		}

	    final List<Feed> items = (List<Feed>) pm.newQuery(query).execute();
	    final Iterator<Feed> iterator = items.iterator();
	    if(iterator.hasNext())
	    {
	    	final Feed next = iterator.next();
	    	
	    	final Text tNext = next.getTitle();
	    	if(tNext!=null)
			{
	    		feed.setTitle(tNext.getValue());
			}
			feed.setLink(next.getUrl());
			final Text tsNext = next.getSubtitle();
			if(tsNext!=null)
			{
				feed.setDescription(tsNext.getValue());
			}
			
	    	final Long id = next.getId();
	    	
	    	final String query4Items = "select from " + RSSItem.class.getName() + " where feedId=="+id + " && readedFlag==null order by modified asc";
	    	//final String query4Items = "select from " + RSSItem.class.getName();
	    	final List<RSSItem> rssItems = (List<RSSItem>) pm.newQuery(query4Items).execute();
	    	LogUtils.logError(log, "INFO: Rows: " + rssItems.size()+": "+query4Items, writer);
			
	    	final Iterator<RSSItem> entries = rssItems.iterator();
	    	
	    	while (entries.hasNext()) {	
	    		final RSSItem next2items = entries.next();
				
				SyndContent description = new SyndContentImpl();
				
				SyndEntry entryExt = new SyndEntryImpl();
				final Text title = next2items.getTitle();
				if(title!=null)
				{
					entryExt.setTitle(title.getValue());
				}
				//entryExt.setLink(next2items.get);
				entryExt.setPublishedDate(next2items.getModified());
				description = new SyndContentImpl();
				description.setType("text/html");
				final Text summury = next2items.getSummury();
				if(summury!=null)
				{
					description.setValue(summury.getValue());
				}
				entryExt.setDescription(description);
				feedEntries.add(entryExt);
			}
	    }

		pm.close();
	
		feed.setEntries(feedEntries);

		SyndFeedOutput output = new SyndFeedOutput();
		try {
			String outputString = output.outputString(feed);
			writer.print(outputString);
		} catch (FeedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		

	}
}
